<template>
    <view class="user-info">
        <image @click.stop="handleUserClick(postDetail.user.id)" class="avatar"
            :src="utils.getAvatarPath(postDetail.user.avatar)" mode="aspectFill"></image>
        <view class="nickname">{{ postDetail.user.nickname }}</view>
        <view class="follow-btn" @click="onFollowToggle" :class="{ 'followed': isFollowing || isMutualFollowing }">
            {{ getMutualFollowText() }}
        </view>
    </view>
    <view v-if="swiperList.length > 0" class="card-swiper">
        <wd-swiper :list="swiperList" :autoplay="false" height="800rpx" :indicator="{ type: 'fraction' }"
            indicatorPosition="bottom-right"></wd-swiper>
    </view>
    <view class="container">
        <text class="content-text">{{ postDetail.content }}</text>
        <view class="time">{{ formatRelativeTime(postDetail.created_at) }}</view>
    </view>
    <!-- 评论列表 -->
    <view class="comment-wrap" v-for="(commentItem, index) in commentList" :key="index">
        <!-- 一级评论 -->
        <view class="comment-item" @click="onCommentItem(commentItem, index)">
            <view class="user-info">
                <image class="avatar" :src="utils.getAvatarPath(commentItem?.user?.avatar)" mode="aspectFill"></image>
                <view class="nickname">{{ commentItem?.user?.nickname }}</view>
            </view>
            <view class="comment-item__content">
                <view class="content-text">{{ commentItem.content }}</view>
                <view class="time">{{ formatRelativeTime(commentItem.created_at) }}</view>
            </view>
        </view>
        <!-- 子级评论 -->
        <view class="chid-wrap">
            <view v-for="(childItem, childIndex) in commentItem.child" :key="childIndex" class="child-item">
                <view class="user-info">
                    <image class="avatar" :src="utils.getAvatarPath(childItem?.user?.avatar)" mode="aspectFill">
                    </image>
                    <view class="nickname">{{ childItem?.user?.nickname }}</view>
                </view>
                <view class="comment-item__content">
                    <view class="content-text">{{ childItem.content }}</view>
                    <view class="time">{{ formatRelativeTime(childItem.created_at) }}</view>
                </view>
            </view>
        </view>
        <view v-if="commentItem.replies_count > 0 && !commentItem.child"
            @click.stop="loadChildComments(commentItem, index)" class="more-child">
            展开{{ commentItem.replies_count }}条回复</view>
        <view v-else-if="commentItem.loadStatus === 'loadmore'" @click.stop="loadChildComments(commentItem, index)"
            class="more-child">展开更多</view>
        <view v-else-if="commentItem.loadStatus === 'nomore'" class="more-child">没有更多了</view>
    </view>
    <q-loadmore :list="commentList" :status="loadStatus" />

    <view style="height: 200rpx"></view>
    <!-- 评论input -->
    <view v-if="showInput" class="reply-input-wrap" :style="{ bottom: keyboardHeight }">
        <textarea class="textarea" :placeholder="replyPlaceholder" v-model="formData.content" :adjust-position="false"
            fixed auto-height :show-confirm-bar="false" :focus="inputFocus"
            @keyboardheightchange="onKeyboardHeightChange" @blur="onBlur" />
        <view class="reply-tool-wrap">
            <view class="tool-item">
                <wd-button theme="light" size="small" @tap="onSubmitReply">发送</wd-button>
            </view>
        </view>
    </view>
    <!-- 评论tool -->
    <view v-else class="reply-data-wrap" @click="onReplyTool">
        <view class="tips-wrap">
            <t-icon name="edit-2" size="30rpx" />
            <text class="txt">说点什么...</text>
        </view>
        <view class="icon-item" @click.stop="onLike">
            <wd-icon v-if="postDetail.is_liked" name="heart-filled" color="#ff4757" size="48rpx"></wd-icon>
            <wd-icon v-else name="heart" size="48rpx" />
            <text class="num" v-if="postDetail.like_count">{{ postDetail.like_count }}</text>
        </view>
        <view class="icon-item" @click.stop="onFavorite">
            <wd-icon v-if="postDetail.is_favorited" name="star-filled" color="#3ac2b8" size="48rpx" />
            <wd-icon v-else name="star" size="48rpx"></wd-icon>
            <text class="num" v-if="postDetail.favorite_count">{{ postDetail.favorite_count }}</text>
        </view>
        <view class="icon-item">
            <button class="reset-button" open-type="share">
                <wd-icon name="share" size="48rpx"></wd-icon>
            </button>
        </view>
    </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { baseAPI } from '@/api/index.js';
import { onLoad, onShow } from '@dcloudio/uni-app';
import utils from '@/utils/utils.js';
import { formatRelativeTime } from '@/utils/timeFormat.js';

//页面公共变量
const postId = ref('');
const postDetail = ref({
    user: {}
});
const isFollowing = ref(false);
const isMutualFollowing = ref(false);
const loadStatus = ref('more');
const swiperList = ref([]);
const showInput = ref(false);
const inputFocus = ref(false);
const keyboardHeight = ref('0px');
const replyPlaceholder = ref('说点什么...');
const commentList = ref([]);
const currentCommentIndex = ref(null)

const formData = reactive({
    parent_id: '0',
    to_user_id: '',
    post_id: null,
    content: ''
});

// 页面生命周期

onLoad((options) => {
    postId.value = options.id;
    formData.post_id = options.id;
    getPostDetail();
});

onShow(() => {
    // 检查关注状态
    if (postDetail.value.user?.id) {
        checkFollowStatus();
    }
});

// 页面函数

function onCommentItem(row, index) {
    showInput.value = true;
    inputFocus.value = true;
    replyPlaceholder.value = `回复:${row.user.nickname}`;
    currentCommentIndex.value = index;

    formData.parent_id = row.id;
    formData.to_user_id = row.user.id;
}

function getParentComments() {
    loadStatus.value = 'loading';
    baseAPI.get('comments/getParentComments', {
        post_id: postId.value
    }).then((res) => {
        if (res.code === 200) {
            commentList.value = res.result.list;

            if (res.result.hasMore) {
                loadStatus.value = 'more';
            } else {
                loadStatus.value = 'nomore';
            }
        }
    });
}

// 加载子级评论
function loadChildComments(row, index) {
    baseAPI.get('comments/getChildComments', {
        parent_id: row.id
    }).then((res) => {
        if (res.code === 200) {
            commentList.value[index].child = res.result.list;

            if (res.result.hasMore) {
                commentList.value[index].loadStatus = 'loadmore';
            } else {
                commentList.value[index].loadStatus = 'nomore';
            }
        }
    });
}

function onSubmitReply() {
    baseAPI.post('comments/publish', formData).then((res) => {
        if (res.code === 200) {
            uni.showToast({
                title: '评论已发布',
                icon: 'none'
            });

            // 清空评论内容
            formData.content = '';

            if (currentCommentIndex.value !== null) {

                loadChildComments(commentList.value[currentCommentIndex.value], currentCommentIndex.value);
            } else {
                commentList.value.unshift(res.result);
            }

        }
    });
}

// 点击评论工具
function onReplyTool() {
    showInput.value = true;
    inputFocus.value = true;
    currentCommentIndex.value = null;

    formData.to_user_id = postDetail.value.user.id;
    formData.parent_id = '0';
}

function getPostDetail() {
    baseAPI
        .get(`post/getInfo`, {
            id: postId.value
        })
        .then((res) => {
            if (res.code === 200) {
                res.result.media.forEach((url) => {
                    swiperList.value.push(utils.imgPath(url));
                });

                postDetail.value = res.result;

                // 获取帖子详情后检查关注状态
                checkFollowStatus();

                getParentComments();
            }
        });
}

function onKeyboardHeightChange() {
    uni.onKeyboardHeightChange((res) => {
        keyboardHeight.value = res.height + 'px';
    });
}

function onBlur() {
    inputFocus.value = false;
    showInput.value = false;
}

// 点赞功能
function onLike() {
    baseAPI.post('post/like', {
        post_id: postId.value
    }).then((res) => {
        if (res.code === 200) {
            postDetail.value.is_liked = res.result.is_liked;

            // 更新点赞数量
            if (res.result.is_liked) {
                postDetail.value.like_count = (postDetail.value.like_count || 0) + 1;
                uni.showToast({
                    title: '点赞成功',
                    icon: 'none'
                });
            } else {
                postDetail.value.like_count = Math.max((postDetail.value.like_count || 1) - 1, 0);
                uni.showToast({
                    title: '取消点赞',
                    icon: 'none'
                });
            }
        }
    }).catch((err) => {
        uni.showToast({
            title: '操作失败',
            icon: 'none'
        });
    });
}

// 检查关注状态
function checkFollowStatus() {
    if (!postDetail.value.user?.id) {
        return;
    }

    baseAPI.get('user/checkFollowStatus', {
        follow_user_id: postDetail.value.user.id
    }).then((res) => {
        if (res.code === 200) {
            isFollowing.value = res.result.is_following;
            isMutualFollowing.value = res.result.is_mutual_following;
        }
    }).catch((err) => {
        console.error('检查关注状态失败:', err);
    });
}

// 关注/取消关注切换
function onFollowToggle() {
    if (!postDetail.value.user?.id) {
        uni.showToast({
            title: '用户信息不完整',
            icon: 'none'
        });
        return;
    }

    const action = isFollowing.value ? 'unfollow' : 'follow';

    baseAPI.post(`user/${action}`, {
        follow_user_id: postDetail.value.user.id
    }).then((res) => {
        if (res.code === 200) {
            isFollowing.value = !isFollowing.value;
            // 重新检查关注状态以更新互相关注状态
            checkFollowStatus();
            uni.showToast({
                title: isFollowing.value ? '关注成功' : '取消关注成功',
                icon: 'none'
            });
        }
    }).catch((err) => {
        uni.showToast({
            title: '操作失败',
            icon: 'none'
        });
    });
}

// 获取互相关注状态的显示文本
function getMutualFollowText() {
    if (isMutualFollowing.value) {
        return '互相关注';
    } else if (isFollowing.value) {
        return '已关注';
    } else {
        return '关注';
    }
}

// 收藏功能
function onFavorite() {
    baseAPI.post('post/favorite', {
        post_id: postId.value
    }).then((res) => {
        if (res.code === 200) {
            postDetail.value.is_favorited = res.result.is_favorited;

            // 更新收藏数量
            if (res.result.is_favorited) {
                postDetail.value.favorite_count = (postDetail.value.favorite_count || 0) + 1;
                uni.showToast({
                    title: '收藏成功',
                    icon: 'none'
                });
            } else {
                postDetail.value.favorite_count = Math.max((postDetail.value.favorite_count || 1) - 1, 0);
                uni.showToast({
                    title: '取消收藏',
                    icon: 'none'
                });
            }
        }
    }).catch((err) => {
        uni.showToast({
            title: '操作失败',
            icon: 'none'
        });
    });
}

// 处理用户点击事件
function handleUserClick(userId) {
    uni.navigateTo({
        url: '/pages/user/profile?id=' + userId
    });
}
</script>

<style lang="scss" scoped>
.user-info {
    display: flex;
    align-items: center;
    padding: $base-spacing;

    .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        border: 1rpx solid #f0f0f0;
    }

    .nickname {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
    }

    .follow-btn {
        background-color: $-color-theme;
        line-height: 1;
        padding: 15rpx 30rpx;
        font-size: 28rpx;
        border-radius: 10rpx;
        margin-left: auto;
        color: #fff;
        transition: all 0.3s ease;

        &.followed {
            background-color: #f0f0f0;
            color: #666;
        }
    }
}

.card-swiper {
    --wot-swiper-radius: 0 !important;
}

.content-text {
    display: block;
}

.time {
    font-size: 24rpx;
    color: #999;
    margin-top: 20rpx;
}

.reply-data-wrap {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    padding: 20rpx;
    border-top: 1px solid #eee;
    background-color: #fff;

    padding-bottom: env(safe-area-inset-bottom); // 兼容iOS 11.2+
    // padding-bottom: constant(safe-area-inset-bottom); // 兼容iOS 11.0-11.1

    .tips-wrap {
        display: flex;
        align-items: center;
        background-color: #eee;
        color: #999;
        padding: 20rpx 40rpx;
        border-radius: 100rpx;
        font-size: 28rpx;
        flex: 1;

        .txt {
            margin-left: 10rpx;
        }
    }

    .icon-item {
        display: flex;
        align-items: center;
        margin-left: 40rpx;

        .num {
            margin-left: 10rpx;
        }
    }
}

.reply-input-wrap {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    padding: 20rpx;
    border-top: 1px solid #eee;
    background-color: #fff;
    display: flex;
    flex-direction: column;

    padding-bottom: env(safe-area-inset-bottom); // 兼容iOS 11.2+
    // padding-bottom: constant(safe-area-inset-bottom); // 兼容iOS 11.0-11.1

    .textarea {
        width: calc(100% - 40rpx);
        border-radius: 10rpx;
        background-color: #eee;
        padding: 20rpx;
    }

    .reply-tool-wrap {
        margin-top: 20rpx;
        display: flex;
        justify-content: flex-end;

        .tool-item {
            margin-left: 20rpx;
        }
    }
}

// 评论列表
.comment-wrap {
    .comment-item {

        padding: 20rpx;

        &:active {
            background-color: #f5f5f5;
        }

        &__content {
            margin-left: 100rpx;
        }
    }

    .chid-wrap {
        margin-top: 20rpx;
        padding-left: 100rpx;

        .user-info {
            .avatar {
                width: 40rpx;
                height: 40rpx;
            }
        }

        .comment-item__content {
            margin-left: 60rpx;
        }
    }

    .more-child {
        margin-top: 20rpx;
        color: #999;
        font-weight: bold;
        margin-left: 160rpx;
    }
}
</style>
